<template>
  <a-drawer
    v-model:visible="innerVisible"
    :footer="null"
    :body-style="{ padding: 0 }"
    :width="drawerWidth"
    :header-style="{ display: 'none' }"
    :centered="true"
    @after-visible-change="afterVisibleChange"
  >
    <div ref="tabsDiv" class="h-full overflow-hidden flex flex-col">
      <a-tabs v-model:activeKey="activeNoticeKey" class="flex-1 notice-overview-tabs">
        <a-tab-pane key="platformNotice" :tab="`平台通知(${noticeCount?.platformCount})`">
          <SpinSkeleton
            :loading="platformNotice.loading"
            first-loading-cls="px-4.5"
            show-empty
            :data="platformNotice.data"
          >
            <div
              v-for="el in platformNotice.data"
              :key="el.id"
              :data-id="el.id"
              class="px-7 pt-7 active:bg-gray-200 hover:bg-gray-50 cursor-pointer"
              @click="noticeObj.platformNotice.showDetail(el)"
            >
              <div class="border-0 border-b border-solid border-color-split pb-3.5">
                <div class="flex flex-row items-center mb-2.5">
                  <div class="flex-1">
                    <a-badge :dot="el.readFlag ? false : true">
                      <span class="text-color-main font-semibold text-lg">{{ el.title }}</span>
                    </a-badge>
                  </div>
                  <div class="text-xs text-color-secondary"> {{ el.createdOn }} </div>
                </div>
                <div class="text-color-secondary">
                  {{ getFrontDomText(el.content) }}
                </div>
              </div>
            </div>
          </SpinSkeleton>
        </a-tab-pane>
        <a-tab-pane key="enterpriseNotice" :tab="`企业通知(${noticeCount?.companyCount})`">
          <SpinSkeleton
            :loading="enterpriseNotice.loading"
            first-loading-cls="px-4.5"
            show-empty
            :data="enterpriseNotice.data"
          >
            <div
              v-for="el in enterpriseNotice.data"
              :key="el.id"
              class="px-7 pt-7 active:bg-gray-200 hover:bg-gray-50 cursor-pointer"
              @click="noticeObj.enterpriseNotice.showDetail(el)"
            >
              <div class="border-0 border-b border-solid border-color-split pb-3.5">
                <div class="flex flex-row items-center mb-2.5">
                  <div class="flex-1">
                    <a-badge :dot="el.readFlag ? false : true">
                      <span class="text-color-main font-semibold text-lg">{{ el.title }}</span>
                    </a-badge>
                  </div>
                  <div class="text-xs text-color-secondary"> {{ el.createdOn }} </div>
                </div>
                <div class="text-color-secondary">
                  {{ getFrontDomText(el.content) }}
                </div>
              </div>
            </div>
          </SpinSkeleton>
        </a-tab-pane>
        <a-tab-pane key="workOrderNotice" :tab="`工单通知(${noticeCount?.workOrderCount})`">
          <SpinSkeleton
            :loading="workOrderNotice.loading"
            first-loading-cls="px-4.5"
            show-empty
            :data="workOrderNotice.data"
          >
            <div
              v-for="el in workOrderNotice.data"
              :key="el.id"
              class="px-7 pt-7 active:bg-gray-200 hover:bg-gray-50 cursor-pointer"
              @click="noticeObj.workOrderNotice.showDetail(el)"
            >
              <div class="border-0 border-b border-solid border-color-split">
                <!-- <div class="flex flex-row items-center mb-3.5">
                  <div>
                    <span class="inline-flex flex-row items-center rounded bg-color-active bg-opacity-10 px-1.5 py-1">
                      <Icon class="text-lg" type="icon-weixiu" />
                      <span class="text-color-active ml-1">维修</span>
                    </span>
                  </div>
                  <div class="flex-1 text-color-main font-semibold ml-3">
                    <a-badge :dot="el.readFlag ? false : true">
                      <span class="text-color-main font-semibold text-lg">{{ el.title }}</span>
                    </a-badge>
                  </div>
                  <div class="text-xs text-color-secondary"> {{ el.createdOn }} </div>
                </div> -->

                <div class="flex-1 mb-4">
                  <a-badge :dot="el.readFlag ? false : true">
                    <span class="font-semibold text-color-main text-xl">{{ el.faultTypeName }}</span>
                  </a-badge>
                </div>
                <p class="text-color-secondary">{{ el.title }}</p>
                <a-descriptions :column="1" :colon="false">
                  <a-descriptions-item label="工单编号"> {{ el.orderCode }} </a-descriptions-item>
                  <a-descriptions-item label="设备名称"> {{ el.equipmentName }} </a-descriptions-item>
                  <a-descriptions-item label="所属项目"> {{ el.projectName }} </a-descriptions-item>
                  <a-descriptions-item label="安装位置"> {{ el.location }} </a-descriptions-item>
                </a-descriptions>
              </div>
            </div>
          </SpinSkeleton>
        </a-tab-pane>
        <a-tab-pane key="warningNotice" :tab="`告警通知(${noticeCount?.alarmCount})`">
          <SpinSkeleton
            :loading="warningNotice.loading"
            first-loading-cls="px-4.5"
            show-empty
            :data="warningNotice.data"
          >
            <AlarmRow
              v-for="(el, i) in warningNotice.data"
              :key="el.id"
              :info="el.alarmEvent"
              :alarm-title="el.title"
              class="px-7"
              :class="{ 'pt-7': i === 0 }"
              hover
              :border="false"
              :inner-border="i < warningNotice.data.length - 1"
              :show-arrow="false"
              :badge-dot="el.readFlag === 0"
              @click="noticeObj.warningNotice.showDetail(el)"
            />
          </SpinSkeleton>
        </a-tab-pane>
      </a-tabs>
      <div class="border-0 border-t border-solid border-color-split flex flex-row items-stretch">
        <a-button
          v-if="activeNoticeKey !== 'warningNotice'"
          class="flex-1 py-4.5 h-auto"
          type="link"
          block
          :loading="clearingUnread"
          :disabled="curUnreadNum === 0"
          @click="handleClearUnread"
        >
          清除未读({{ curUnreadNum }})
        </a-button>
        <div v-if="activeNoticeKey !== 'warningNotice'" class="w-px my-4.5 bg-color-split"> </div>
        <a-button class="flex-1 py-4.5 h-auto" type="link" block @click="toAll">查看全部</a-button>
      </div>
    </div>
    <MessageDetail
      v-if="curMes"
      v-model:visible="mesDetailVisible"
      :advice-type="curAdviceType"
      :message="curMes"
      :mask="true"
      :get-container="getContainer"
      @load="onMesDetailLoad"
    ></MessageDetail>
    <WorkOrderDetails
      v-if="curOrderId"
      v-model:visible="orderDetailVisible"
      :works-order-id="curOrderId"
      :get-container="getContainer"
      :mask="true"
    />
    <ServiceApplyDetails
      v-model:visible="serviceDetailVisible"
      v-model:serviceOrderId="curOrderId"
      :get-container="getContainer"
      :mask="true"
      :show-btn="false"
    />
    <AlarmModal
      v-model:id="curAlarmId"
      :is-modal="false"
      drawer-container-selector="body"
      :work-order-container="getContainer"
      @success-fn="alarmOk"
    />
  </a-drawer>
</template>
<script lang="ts" setup>
import { computed, onMounted, Ref, ref, watch, nextTick } from "vue";
import { useHomeStore } from "/@/stores/home";
import {
  adviceCount,
  getFrontData,
  Api,
  platformClearUnread,
  companyClearUnread,
  workOrderClearUnread,
  alarmClearUnread,
  readByAdviceId,
} from "/@/api/aiot/notifiManage";
import { CoutItem, NotifiItem, ParCoutItem, ReadAdviceItem } from "/@/api/aiot/notifiManage/models";
import { message } from "ant-design-vue";
import { getFrontDomText } from "/@/utils/dom";
import router from "/@/router";
import AlarmModal from "/@/views/aiot/enterprise/AlarmCenter/AlarmModal.vue";

const props = defineProps<{
  visible: boolean;
}>();

const emits = defineEmits(["update:visible"]);
const serviceOrderId = ref();
const serviceDetailVisible = ref<boolean>(false);

const innerVisible = ref(false);
watch(
  () => props.visible,
  (v) => {
    innerVisible.value = v;
  }
);
watch(innerVisible, (v) => {
  if (!v) {
    curAlarmId.value = "";
  }
  emits("update:visible", v);
});

const homeStore = useHomeStore();
interface NoticeTabItem {
  unreadNum: number;
  loading: boolean;
  data: NotifiItem[];
}
const platformNotice = ref<NoticeTabItem>({
  unreadNum: 0,
  loading: false,
  data: [],
});
const enterpriseNotice = ref<NoticeTabItem>({
  unreadNum: 0,
  loading: false,
  data: [],
});
const workOrderNotice = ref<NoticeTabItem>({
  unreadNum: 0,
  loading: false,
  data: [],
});
const warningNotice = ref<NoticeTabItem>({
  unreadNum: 0,
  loading: false,
  data: [],
});

//清除单条未读
async function clear1Unred(el: NotifiItem, key: NoticeKey, adviceType: ReadAdviceItem["adviceType"]) {
  if (el.readFlag) return;
  const re = await readByAdviceId({ adviceId: el.id, adviceType }, false);
  if (re) {
    refreshUnread();
    reloadNotice(key);
  }
}

const curAlarmId = ref("");
const alarmVisible = ref(false);
const curAlarmItem = ref<NotifiItem>();

type NoticeKey = "platformNotice" | "enterpriseNotice" | "workOrderNotice" | "warningNotice";
const noticeObj: Record<
  NoticeKey,
  {
    ref: Ref<NoticeTabItem>;
    url: string;
    clearUnread: (loading?: boolean) => Promise<boolean | null>;
    showDetail: (el: NotifiItem) => void;
  }
> = {
  platformNotice: {
    ref: platformNotice,
    url: Api.platformPage,
    clearUnread: platformClearUnread,
    showDetail(el) {
      showMesDetail(el, "PLATFORM");
    },
  },
  enterpriseNotice: {
    ref: enterpriseNotice,
    url: Api.companyPage,
    clearUnread: companyClearUnread,
    showDetail(el) {
      showMesDetail(el, "COMPANY");
    },
  },
  workOrderNotice: {
    ref: workOrderNotice,
    url: Api.workOrderPage,
    clearUnread: workOrderClearUnread,
    showDetail(el) {
      clear1Unred(el, "workOrderNotice", "WORK_ORDER");
      showOrderDetail(el.workOrderId, el.workOrderClass);
    },
  },
  warningNotice: {
    ref: warningNotice,
    url: Api.alarmPage,
    clearUnread: alarmClearUnread,
    showDetail(el) {
      curAlarmItem.value = el;
      clear1Unred(el, "warningNotice", "ALARM");
      curAlarmId.value = el.alarmEventId;
      alarmVisible.value = true;
    },
  },
};
function alarmOk() {
  if (curAlarmItem.value) {
    clear1Unred(curAlarmItem.value, "warningNotice", "ALARM");
  }
}

const activeNoticeKey = ref<"" | NoticeKey>("");
async function reloadNotice(key: NoticeKey | "") {
  if (!key) return;
  const target = noticeObj[key];
  if (target) {
    target.ref.value.loading = true;
    const data = await getFrontData(target.url);
    if (data) {
      target.ref.value.data = data.records;
    }
    target.ref.value.loading = false;
  }
}
watch(activeNoticeKey, (key) => {
  refreshUnread();
  reloadNotice(key);
});

const tabsDiv = ref<HTMLDivElement>();
const drawerWidth = ref(450);
const tabsPaddingHorizontal = 24;
function resize() {
  if (tabsDiv.value) {
    const navListEl: HTMLDivElement | null = tabsDiv.value.querySelector("div.ant-tabs-nav-list");
    if (navListEl) {
      drawerWidth.value = navListEl.offsetWidth + tabsPaddingHorizontal * 4;
    }
  }
}
function afterVisibleChange(visible) {
  if (visible) {
    resize();
    if (activeNoticeKey.value === "") {
      activeNoticeKey.value = "platformNotice";
    }
  }
}
const noticeCount = ref<CoutItem | ParCoutItem>();
async function refreshUnread() {
  const data = await adviceCount({});
  noticeCount.value = data || {};
  if (data) {
    const sumUnreadCount =
      +data.companyUnreadCount + +data.platformUnreadCount + +data.workOrderUnreadCount + +data.alarmUnreadCount;
    homeStore.sumUnreadCount = sumUnreadCount;
    enterpriseNotice.value.unreadNum = +data.companyUnreadCount;
    workOrderNotice.value.unreadNum = +data.workOrderUnreadCount;
    platformNotice.value.unreadNum = +data.platformUnreadCount;
    warningNotice.value.unreadNum = +data.alarmUnreadCount;
  }
}
homeStore.refreshUnread = refreshUnread;
onMounted(() => {
  refreshUnread();
});
//当前选中页签的消息未读数量
const curUnreadNum = computed(() => {
  if (!activeNoticeKey.value) return 0;
  const target = noticeObj[activeNoticeKey.value];
  return target ? target.ref.value.unreadNum : 0;
});
const clearingUnread = ref(false);
async function handleClearUnread() {
  const target = noticeObj[activeNoticeKey.value];
  if (target) {
    clearingUnread.value = true;
    const re = await target.clearUnread(false);
    if (re) {
      message.success("操作成功");
      await refreshUnread();
      reloadNotice(activeNoticeKey.value);
    }
    clearingUnread.value = false;
  }
}
function toAll() {
  innerVisible.value = false;
  const obj = {
    platformNotice: "plateform",
    enterpriseNotice: "enterprise",
    workOrderNotice: "workorder",
    warningNotice: "alarm",
  };
  homeStore.curNoticeKey = obj[activeNoticeKey.value];
  router.push("/aiot/message/messageCenter");
}
/**
 * MessageDetail
 */
const mesDetailVisible = ref(false);
const curAdviceType = ref<ReadAdviceItem["adviceType"]>("PLATFORM");
const curMes = ref<NotifiItem>();
function getContainer() {
  return document.body;
}
function showMesDetail(item: NotifiItem, adviceType: ReadAdviceItem["adviceType"]) {
  curMes.value = item;
  curAdviceType.value = adviceType;
  nextTick(() => {
    mesDetailVisible.value = true;
  });
}
function onMesDetailLoad(item: NotifiItem) {
  if (item.title) {
    //消息详情加载成功回调
    refreshUnread();
    reloadNotice(activeNoticeKey.value);
  }
}
/**
 * order detail
 */
const orderDetailVisible = ref(false);
const curOrderId = ref("");
function showOrderDetail(orderId: string, workOrderClass: string) {
  curOrderId.value = orderId;
  if (workOrderClass === "service") {
    nextTick(() => {
      serviceDetailVisible.value = true;
    });
  } else {
    nextTick(() => {
      orderDetailVisible.value = true;
    });
  }
}
</script>
<stlye lang="less">
.notice-overview-tabs {
  .ant-tabs-nav {
    margin-bottom: 0;
  }
  .ant-tabs-nav-wrap {
    padding: 0 24px;
  }
  .ant-tabs-tab {
    padding: 16px 0;
  }
  .ant-tabs-tab + .ant-tabs-tab {
    margin: 0 0 0 24px;
  }
  .ant-tabs-tab-btn {
    font-size: 16px;
  }

  .ant-descriptions-item-label {
    width: 80px;
    color: @color-secondary;
  }
  .ant-tabs-content {
    height: 100%;
    overflow: hidden;
  }
  .ant-tabs-tabpane {
    height: 100%;
    overflow: auto;
  }
}
</stlye>
